/*
 * ========================================================
 * Copyright(c) 2014 杭州龙骞科技-版权所有
 * ========================================================
 * 本软件由杭州龙骞科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 * http://www.hzdracom.com/
 * ========================================================
 */
package com.netease.nim.demo.main.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;

import com.netease.nim.demo.base.YXBaseActivity;
import com.netease.nim.demo.common.fragment.TFragment;
import com.netease.nim.demo.contact.cache.ContactDataCache;
import com.netease.nim.demo.contact.cache.TeamDataCache;
import com.netease.nim.demo.contact.protocol.ContactHttpClient;
import com.netease.nim.demo.main.fragment.HomeFragment;
import com.netease.nim.demo.session.activity.P2PMessageActivity;
import com.netease.nim.demo.session.activity.TeamMessageActivity;
import com.netease.nimlib.sdk.NimIntent;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.shwread.android.qysw10000243.R;

import java.util.ArrayList;


/**
 * @Project： qysw_1.0.8_dev
 * @Title：ContactMainActivity
 * @Description：
 * @Author：wayne
 * @Date：2015年5月25日下午4:10:02
 */
public class ContactMainActivity
        extends
        YXBaseActivity
{
	private final String TAG = "ContactMainActivity";
	
	private HomeFragment mainFragment;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main_tab);
		
		onParseIntent();
		showMainFragment();
	}
	
	@Override
	protected void onNewIntent(Intent intent) {
		setIntent(intent);
		onParseIntent();
	}
	
	@Override
	public void onBackPressed() {
		if (mainFragment != null)
		{
			if (mainFragment.onBackPressed())
			{
				return;
			}
			else
			{
				super.onBackPressed();
			}
		}
		else
		{
			super.onBackPressed();
		}
	}
	
	private void onParseIntent() {
		Intent intent = getIntent();
		if (intent.hasExtra(NimIntent.EXTRA_NOTIFY_CONTENT))
		{
//			IMMessage message = (IMMessage) getIntent().getSerializableExtra(NimIntent.EXTRA_NOTIFY_CONTENT);
			ArrayList<IMMessage> messages = (ArrayList<IMMessage>) getIntent().getSerializableExtra(NimIntent.EXTRA_NOTIFY_CONTENT);
			switch (messages.get(0).getSessionType()) {
				case P2P:
					P2PMessageActivity.start(this, messages.get(0).getSessionId());
					break;
				case Team:
					TeamMessageActivity.start(this, messages.get(0).getSessionId());
					break;
				default:
					break;
			}
		}
	}
	
	private void showMainFragment() {
		prepareCacheData();
		
		if (mainFragment == null)
		{
			mainFragment = new HomeFragment();
			switchFragmentContent(mainFragment);
		}
		
		new Handler(getMainLooper()).postDelayed(new Runnable()
		{
			@Override
			public void run() {
				prepareRemoteData();
			}
		}, 500);
	}
	
	protected void switchFragmentContent(TFragment fragment) {
		FragmentManager fm = getSupportFragmentManager();
		FragmentTransaction transaction = fm.beginTransaction();
		transaction.replace(fragment.getFragmentId(), fragment);
		try
		{
			transaction.commitAllowingStateLoss();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	private void prepareRemoteData() {
		// request buddies data
		if (!ContactDataCache.getInstance().isBuddyCacheDataEmpty()) { return; }
		
		Log.i(TAG, "request buddies data...");
		//        ContactHttpClient.getInstance().getAddressBook(new IContactHttpCallback<List<Buddy>>() {
		//            @Override
		//            public void onSuccess(List<Buddy> buddies) {
		//                ContactDataCache.getInstance().addOrUpdateBuddies(buddies);
		//                Log.i(TAG, "request buddies data completed, data size =" + buddies.size());
		//            }
		//
		//            @Override
		//            public void onFailed(int code, String errorMsg) {
		//
		//            }
		//        });
	}
	
	private void prepareCacheData() {
		ContactHttpClient.getInstance().getTokenOnLogin();
		ContactDataCache.getInstance().initBuddyCache(null);
		TeamDataCache.getInstance().initTeamCache();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		mainFragment.onActivityResult(requestCode, resultCode, data);
		if(resultCode == 10086)
			finish();
	}
}
